package com.chengqj.service.impl;

import com.chengqj.dao.UserDO;
import com.chengqj.repository.UserRepository;
import com.chengqj.service.IUserService;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Optional;

@DubboService(interfaceClass = IUserService.class)
public class UserInfoService implements IUserService {
    /**
     * [mongo] 用户
     */
    @Autowired
    private UserRepository userRepository;

    @Override
    public boolean prepare(BusinessActionContext actionContext, String userId) {
//        System.out.println("user   prepare ");
//
//        Optional<UserDO> userOptional = userRepository.findById(userId);
//        if (userOptional.isPresent()) {
//            return true;
//        }
        return true;
    }

    @Override
    public boolean commit(BusinessActionContext actionContext) {
        System.out.println("user   commit ");

        String userId = (String) actionContext.getActionContext("userId");
        Optional<UserDO> userOptional = userRepository.findById(userId);
        if (userOptional.isPresent()) {
            UserDO userDO = userOptional.get();
            userDO.setAmount(userDO.getAmount() - 100);
            userRepository.save(userDO);
            return true;
        }
        return false;
    }

    @Override
    public boolean rollback(BusinessActionContext actionContext) {
        System.out.println("rollback");
        return true;
    }
}
